using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

namespace DOTS.DOD.LESSON9
{
    [BurstCompile]
    [RequireMatchingQueriesForUpdate]
    [UpdateInGroup(typeof(SpawnerBlobSystemGroup))]
    partial struct GenerateSpawnerSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<SpawnerGenerator>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            var generator = SystemAPI.GetSingleton<SpawnerGenerator>();
            var spawners =
                CollectionHelper.CreateNativeArray<Entity>(4 * generator.RadiusX * generator.RadiusZ, Allocator.Temp);
            state.EntityManager.Instantiate(generator.SpawnerProtoType, spawners);

            int count = 0;
            foreach (var spawner in spawners)
            {
                int x = count % (generator.RadiusX * 2) - generator.RadiusX;
                int z = count / (generator.RadiusX * 2) - generator.RadiusZ;
                var pos = new float3(x * 1.1f, 0, z * 1.1f);
                var transform = SystemAPI.GetComponentRW<LocalTransform>(spawner);
                transform.ValueRW.Position = pos;
                count++;
            }

            spawners.Dispose();
            state.Enabled = false;
        }
    }
}